package com.example.demo.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;



/**
 * @author admin
 */
public class JwtUtil {
    //私钥，用于签名和验证
    private static final String SECRET_KEY = "your-secret-key-with-a-very-long-string-to-meet-the-64-byte-requirement-for-hs512!";
    //过期时间
    private static long EXPIRE_TIME = 60000;
    private static final Logger log = LoggerFactory.getLogger(JwtUtil.class);

    /**
     *生成JWT token
     */
    public static String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                //签发时间
                .setIssuedAt(new Date())
                //过期时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY.getBytes())
                .compact();
    }

    /**
     * 解析token
     */
    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY.getBytes())
                .parseClaimsJws(token)
                .getBody();
    }
    /**
     * 验证token是否有效
     */
    public static boolean validateToken(String token) {
        try{
            parseToken(token);
            return true;
        }catch(Exception e){
            return false;
        }
    }

    /***
     * 获取token中的用户名
     */
    public static String getUsername(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }
}
